﻿<%@ WebHandler Language="C#" Class="KeyProcessRecordHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
/**
 * Description: 其他单据打印
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2023.8.25
 */

public class KeyProcessRecordHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    EmployeeMaintPageBusiness employeeMaintBusiness = new EmployeeMaintPageBusiness();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getFactory":
                    getFactory(context);//查询分厂
                    break;
                case "getCurrentUserInfo":
                    getCurrentUserInfo(context);//获取当前用户信息
                    break;
                case "getData":
                    getData(context);//批次数据
                    break;
                case "getContainerInfo":
                    getContainerInfo(context);//获取流水卡信息
                    break;
                case "saveTeachConfirmData":
                    saveTeachConfirmData(context);//保存技术员确认信息
                    break;
                case "saveCheckConfirmData":
                    saveCheckConfirmData(context);//保存检验员确认信息
                    break;
                case "removeTeachConfirmData":
                    removeTeachConfirmData(context);//移除技术员确认信息
                    break;
                case "removeCheckConfirmData":
                    removeCheckConfirmData(context);//移除检验确认信息
                    break;
                case "getTeachOrCheckConfirmData":
                    getTeachOrCheckConfirmData(context);//获取技术员/检验员确认信息
                    break;
                case "savePrintSession":
                    savePrintSession(context);//保存质保单打印session
                    break;
                case "exportData":
                    ExportSearchData(context);//导出查询数据
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";

            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 导出查询数据 
    /// </summary>
    /// <param name="context"></param>
    private void ExportSearchData(HttpContext context)
    {
        string sql = @"
       SELECT c.mfgordername 订单号,c.productname 件号,c.containername 批次号,c.workflowstepname 在制工序,c.qty 在制数,DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS 批次类型,
       c.plannedstartdate 订单开始时间,c.plannedcompletiondate 计划完成时间,f.factoryname 分厂,cid.createdate 入库时间,
       e.fullname 技术员,cq.techconfirmdate 技术确认时间,cq.techconfirmnote 技术确认备注,e2.fullname 检验员,cq.checkconfirmdate 检验确认时间,
       ee.fullname 工艺员,cq.spindlenode 锭节点,
       DECODE(c.isinstore,-1,'领料中',1,'完工入库',0,'在制') 批次状态
        FROM containercurrentinfo c
        LEFT JOIN factory f ON f.factoryid = c.originalfactoryid
        LEFT JOIN containerinstore cid ON cid.charg = c.containername
        LEFT JOIN containerqualityensure cq ON cq.containerid = c.containerid
        LEFT JOIN employee e ON e.employeeid = cq.techconfirmemployee
        LEFT JOIN employee e2 ON e2.employeeid = cq.checkconfirmemployee
        LEFT JOIN employee ee ON ee.employeeid = c.techniqueemployeeid
        WHERE c.containerstatus <> '2' {0}

        UNION ALL 

        SELECT subc.mfgordername 订单号,subc.productname 件号,subc.containername 批次号,subc.workflowstepname 在制工序,subc.qty 在制数,DECODE(subc.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS 批次类型,
       subc.plannedstartdate 订单开始时间,subc.plannedcompletiondate 计划完成时间,f.factoryname 分厂,cid.createdate 入库时间,
       e.fullname 技术员,cq.techconfirmdate 技术确认时间,cq.techconfirmnote 技术确认备注,e2.fullname 检验员,cq.checkconfirmdate 检验确认时间,
       ee.fullname 工艺员,cq.spindlenode 锭节点,
       DECODE(subc.isinstore,-1,'领料中',1,'完工入库',0,'在制') 批次状态
        FROM containercurrentinfo c
        INNER JOIN containersubcontainer csc ON csc.containerid = c.containerid
        INNER JOIN containercurrentinfo subc ON subc.containerid = csc.subcontainerid AND subc.containerstatus <> '2'
        LEFT JOIN factory f ON f.factoryid = subc.originalfactoryid
        LEFT JOIN containerinstore cid ON cid.charg = subc.containername
        LEFT JOIN containerqualityensure cq ON cq.containerid = subc.containerid
        LEFT JOIN employee e ON e.employeeid = cq.techconfirmemployee
        LEFT JOIN employee e2 ON e2.employeeid = cq.checkconfirmemployee
        LEFT JOIN employee ee ON ee.employeeid = subc.techniqueemployeeid
        WHERE c.containerstatus <> '2' {0}";

        string sqlWhere = string.Empty;
        //承制分厂
        if (!string.IsNullOrWhiteSpace(context.Request.Form["factoryid"].ToString()))
        {
            sqlWhere += string.Format(" AND c.originalfactoryid = '{0}'", context.Request.Form["factoryid"].ToString());
        }

        //扫描批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["scanContainerName"].ToString()))
        {
            string scanContainerName = commonBusiness.ContainerScan(context.Request.Form["scanContainerName"].ToString());
            sqlWhere += string.Format(" AND (c.togetherflag = '{0}' OR c.containername = '{0}')", scanContainerName);
        }

        //扫描订单号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["mfgordername"].ToString()))
        {
            sqlWhere += string.Format(" AND c.mfgordername = '{0}'", context.Request.Form["mfgordername"].ToString());
        }

        //零件图号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["productname"].ToString()))
        {
            sqlWhere += string.Format(" AND c.productname LIKE '%{0}%'", context.Request.Form["productname"].ToString());
        }

        //大批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["togetherflag"].ToString()))
        {
            sqlWhere += string.Format(" AND c.togetherflag LIKE '%{0}%'", context.Request.Form["togetherflag"].ToString());
        }

        //工序号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["specno"].ToString()))
        {
            sqlWhere += string.Format(" AND c.specno = '{0}'", context.Request.Form["specno"].ToString());
        }

        //入库时间
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredatestart"].ToString()))
        {
            sqlWhere += string.Format(" AND TRUNC(cid.createdate) >= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredatestart"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredateend"].ToString()))
        {
            sqlWhere += string.Format(" AND TRUNC(cid.createdate) <= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredateend"].ToString());
        }

        //打印类型
        //if (context.Request.Form["ddlType"].ToString() == "关键过程")
        //{
        //    sqlWhere += " AND sc.keycheck = 1";
        //}

        //批次状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlContainerStatus"].ToString()))
        {
            string ddlContainerStatus = context.Request.Form["ddlContainerStatus"].ToString();
            if (ddlContainerStatus == "在制")
            {
                sqlWhere += " AND c.isinstore = 0";
            }
            else if (ddlContainerStatus == "完工入库")
            {
                sqlWhere += " AND c.isinstore = 1";
            }
            else
            {
                sqlWhere += " AND c.isinstore = -1";
            }
        }

        //确认状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlConfirmStatus"].ToString()))
        {
            string ddlConfirmStatus = context.Request.Form["ddlConfirmStatus"].ToString();
            if (ddlConfirmStatus == "已确认")
            {
                sqlWhere += " AND cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL";
            }
            else
            {
                sqlWhere += " AND NOT (cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL)";
            }
        }

        //if (!string.IsNullOrWhiteSpace(context.Request.Form["workflowEmpName"].ToString())) //工艺员查询
        //{
        //    sqlWhere += string.Format(" AND ee.fullname like '%{0}%'", context.Request.Form["workflowEmpName"].ToString());
        //}
        if (!string.IsNullOrWhiteSpace(context.Request.Form["printType"].ToString()) && context.Request.Form["printType"].ToString().Equals("1")) //振动攻关查询
        {
            sqlWhere += @" and exists (
            select 1 from workflowstep ws 
            left join stepcheckpoint sc on sc.workflowstepid =ws.workflowstepid 
            where ws.workflowid=decode(c.containerstatus,1,c.workflowid,c.bsworkflowid) and sc.checktype ='5'
            )";
        }
        DataTable dtData = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, sqlWhere));
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtData);
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("质保单管理查询导出记录"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    //获取分厂
    void getFactory(HttpContext context)
    {
        string strSql = @"SELECT f.factoryid,f.factoryname FROM factory f";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "获取成功", DBTable = dt }));
    }

    void getCurrentUserInfo(HttpContext context)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("employeeid");
        dt.Columns.Add("fullname");
        dt.Columns.Add("factoryid");
        DataRow dr = dt.NewRow();
        dr["employeeid"] = m_UserInfo.EmployeeID;
        dr["fullname"] = m_UserInfo.FullName;
        dr["factoryid"] = m_UserInfo.FactoryID;
        dt.Rows.Add(dr);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = dt }));
    }

    // 查询页面表格数据
    void getData(HttpContext context)
    {
        string sql = @"
SELECT c.productname,c.productid,c.workflowstepname,c.workflowstepid,c.specno, c.workflowid,c.workflowstepsequence AS SEQUENCE,c.togetherflag,
       c.containertype,DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS containertypename,c.mfgordername,c.planqty,
       c.plannedstartdate,c.plannedcompletiondate,c.workcentername,c.workcenterid,c.factoryid,c.productdescription,c.productrevision,c.isselfmfg,
       (c.productname||'/'||c.containerno) productbatch,
       SUM(c.qty) AS wipqty ,'' containerid,''containername,NULL workreportnum,'' facontianerid,
       NULL firstchecknum,NULL stepchecknum,''iskey,''specname,''specrevision,''parentspecno,
       NVL(c.nonconformingnum,0) nonconformingnum,f.factoryname,MAX(cid.createdate) instoredate,
       DECODE(c.isinstore,-1,'领料中',1,'完工入库',0,'在制') status,'--' ckstatus
FROM containercurrentinfo c
LEFT JOIN factory f ON f.factoryid = c.originalfactoryid
--LEFT JOIN stepcheckpoint sc ON c.productid=sc.productid AND sc.workflowstepid=c.workflowstepid
LEFT JOIN containerinstore cid ON cid.charg = c.containername
LEFT JOIN containerqualityensure cq ON cq.containerid = c.containerid
LEFT JOIN employee ee ON ee.employeeid = c.techniqueemployeeid
WHERE c.containerstatus <> '2' AND c.containertype='7' ";
        //承制分厂
        if (!string.IsNullOrWhiteSpace(context.Request.Form["factoryid"].ToString()))
        {
            sql += string.Format(" AND c.originalfactoryid = '{0}'", context.Request.Form["factoryid"].ToString());
        }

        //扫描批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["scanContainerName"].ToString()))
        {
            string scanContainerName = commonBusiness.ContainerScan(context.Request.Form["scanContainerName"].ToString());
            sql += string.Format(" AND (c.togetherflag = '{0}' OR c.containername = '{0}')", scanContainerName);
        }

        //扫描订单号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["mfgordername"].ToString()))
        {
            sql += string.Format(" AND c.mfgordername = '{0}'", context.Request.Form["mfgordername"].ToString());
        }

        //零件图号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["productname"].ToString()))
        {
            sql += string.Format(" AND c.productname LIKE '%{0}%'", context.Request.Form["productname"].ToString());
        }

        //大批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["togetherflag"].ToString()))
        {
            sql += string.Format(" AND c.togetherflag LIKE '%{0}%'", context.Request.Form["togetherflag"].ToString());
        }

        //工序号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["specno"].ToString()))
        {
            sql += string.Format(" AND c.specno = '{0}'", context.Request.Form["specno"].ToString());
        }

        //入库时间
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredatestart"].ToString()))
        {
            sql += string.Format(" AND TRUNC(cid.createdate) >= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredatestart"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredateend"].ToString()))
        {
            sql += string.Format(" AND TRUNC(cid.createdate) <= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredateend"].ToString());
        }

        //打印类型
        //if (context.Request.Form["ddlType"].ToString() == "关键过程")
        //{
        //    sql += " AND sc.keycheck = 1";
        //}

        //批次状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlContainerStatus"].ToString()))
        {
            string ddlContainerStatus = context.Request.Form["ddlContainerStatus"].ToString();
            if (ddlContainerStatus == "在制")
            {
                sql += " AND c.isinstore = 0";
            }
            else if (ddlContainerStatus == "完工入库")
            {
                sql += " AND c.isinstore = 1";
            }
            else
            {
                sql += " AND c.isinstore = -1";
            }
        }

        //确认状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlConfirmStatus"].ToString()))
        {
            string ddlConfirmStatus = context.Request.Form["ddlConfirmStatus"].ToString();
            if (ddlConfirmStatus == "已确认")
            {
                sql += " AND cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL";
            }
            else
            {
                sql += " AND NOT (cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL)";
            }
        }

        //if (!string.IsNullOrWhiteSpace(context.Request.Form["workflowEmpName"].ToString())) //工艺员查询
        //{
        //    sql += string.Format(" AND ee.fullname like '%{0}%'", context.Request.Form["workflowEmpName"].ToString());
        //}
        if (!string.IsNullOrWhiteSpace(context.Request.Form["printType"].ToString()) && context.Request.Form["printType"].ToString().Equals("1")) //振动攻关查询
        {
            sql += @" and exists (
            select 1 from workflowstep ws 
            left join stepcheckpoint sc on sc.workflowstepid =ws.workflowstepid 
            where ws.workflowid=decode(c.containerstatus,1,c.workflowid,c.bsworkflowid) and sc.checktype ='5'
            )";
        }

        sql += @"
GROUP BY c.productid, c.productname, c.workflowstepname,c.workflowstepid, c.workflowid, c.workflowstepsequence, c.specno,
         c.togetherflag, c.containertype,c.mfgordername,c.planqty, c.plannedstartdate, c.plannedcompletiondate,
         c.workcentername,c.workcenterid,c.factoryid,c.productdescription,c.productrevision,c.nonconformingnum,c.isselfmfg,c.containerno,f.factoryname,c.isinstore
UNION ALL

SELECT c.productname,c.productid,c.workflowstepname,c.workflowstepid,c.specno, c.workflowid,c.workflowstepsequence AS SEQUENCE,c.togetherflag,
       c.containertype,DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS containertypename,c.mfgordername,c.planqty,
       c.plannedstartdate,c.plannedcompletiondate,c.workcentername,c.workcenterid,c.factoryid,c.productdescription,c.productrevision,c.isselfmfg,
       (c.productname||'/'||c.containerno) productbatch,   
       c.qty AS wipqty , c.containerid,c.containername,c.workreportnum,c.containerid AS facontianerid,
       c.firstchecknum,c.stepchecknum,c.iskey,c.specname,c.specrevision,c.parentspecno,
       NVL(c.nonconformingnum,0) nonconformingnum,f.factoryname,cid.createdate,DECODE(c.isinstore,-1,'领料中',1,'完工入库',0,'在制') status,
       CASE WHEN cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL THEN '已确认' ELSE '未确认' END ckstatus
FROM containercurrentinfo c 
LEFT JOIN factory f ON f.factoryid = c.originalfactoryid
--LEFT JOIN stepcheckpoint sc ON c.productid=sc.productid AND sc.workflowstepid=c.workflowstepid
LEFT JOIN containerinstore cid ON cid.charg = c.containername
LEFT JOIN containerqualityensure cq ON cq.containerid = c.containerid
LEFT JOIN employee ee ON ee.employeeid = c.techniqueemployeeid
WHERE c.containerstatus <> '2' AND c.containertype<>'7'";
        //承制分厂
        if (!string.IsNullOrWhiteSpace(context.Request.Form["factoryid"].ToString()))
        {
            sql += string.Format(" AND c.originalfactoryid = '{0}'", context.Request.Form["factoryid"].ToString());
        }

        //扫描批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["scanContainerName"].ToString()))
        {
            string scanContainerName = commonBusiness.ContainerScan(context.Request.Form["scanContainerName"].ToString());
            sql += string.Format(" AND c.togetherflag = '{0}'", scanContainerName);
        }

        //扫描订单号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["mfgordername"].ToString()))
        {
            sql += string.Format(" AND c.mfgordername = '{0}'", context.Request.Form["mfgordername"].ToString());
        }

        //零件图号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["productname"].ToString()))
        {
            sql += string.Format(" AND c.productname LIKE '%{0}%'", context.Request.Form["productname"].ToString());
        }

        //大批次号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["togetherflag"].ToString()))
        {
            sql += string.Format(" AND c.togetherflag LIKE '%{0}%'", context.Request.Form["togetherflag"].ToString());
        }

        //工序号
        if (!string.IsNullOrWhiteSpace(context.Request.Form["specno"].ToString()))
        {
            sql += string.Format(" AND c.specno = '{0}'", context.Request.Form["specno"].ToString());
        }

        //入库时间
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredatestart"].ToString()))
        {
            sql += string.Format(" AND TRUNC(cid.createdate) >= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredatestart"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["instoredateend"].ToString()))
        {
            sql += string.Format(" AND TRUNC(cid.createdate) <= to_date('{0}','yyyy/mm/dd')", context.Request.Form["instoredateend"].ToString());
        }

        //打印类型
        //if (context.Request.Form["ddlType"].ToString() == "关键过程")
        //{
        //    sql += " AND sc.keycheck = 1";
        //}

        //批次状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlContainerStatus"].ToString()))
        {
            string ddlContainerStatus = context.Request.Form["ddlContainerStatus"].ToString();
            if (ddlContainerStatus == "在制")
            {
                sql += " AND c.isinstore = 0";
            }
            else if (ddlContainerStatus == "完工入库")
            {
                sql += " AND c.isinstore = 1";
            }
            else
            {
                sql += " AND c.isinstore = -1";
            }
        }

        //确认状态
        if (!string.IsNullOrWhiteSpace(context.Request.Form["ddlConfirmStatus"].ToString()))
        {
            string ddlConfirmStatus = context.Request.Form["ddlConfirmStatus"].ToString();
            if (ddlConfirmStatus == "已确认")
            {
                sql += " AND cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL";
            }
            else
            {
                sql += " AND NOT (cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL)";
            }
        }

        //if (!string.IsNullOrWhiteSpace(context.Request.Form["workflowEmpName"].ToString())) //工艺员查询
        //{
        //    sql += string.Format(" AND ee.fullname like '%{0}%'", context.Request.Form["workflowEmpName"].ToString());
        //}

        if (!string.IsNullOrWhiteSpace(context.Request.Form["printType"].ToString()) && context.Request.Form["printType"].ToString().Equals("1")) //振动攻关查询
        {
            sql += @" and exists (
            select 1 from containersubcontainer csc
            left join containercurrentinfo subc ON subc.containerid = csc.subcontainerid 
            left join workflowstep ws on ws.workflowid=decode(subc.containerstatus,1,subc.workflowid,subc.bsworkflowid)
            left join stepcheckpoint sc on sc.workflowstepid =ws.workflowstepid 
            where csc.containerid = c.containerid and sc.checktype ='5'
            )";
        }
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    // 查询大批次下各流水卡
    void getContainerInfo(HttpContext context)
    {
        string strSql = @"
SELECT cci.containerid,cci.containername,cci.teamname,cci.qty,cci.teamname,cci.workflowid,cci.techniqueemployeeid,ee.fullname containertechemp,
       CASE WHEN cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL THEN '已确认' ELSE '未确认' END status,
       e.fullname techemp,cq.techconfirmdate,cq.techconfirmnote,e2.fullname checkemp,cq.checkconfirmdate,cq.checkconfirmnote,cq.spindlenode
FROM containercurrentinfo cci
LEFT JOIN containerqualityensure cq ON cq.containerid = cci.containerid
LEFT JOIN employee e ON e.employeeid = cq.techconfirmemployee
LEFT JOIN employee e2 ON e2.employeeid = cq.checkconfirmemployee
LEFT JOIN employee ee ON ee.employeeid = cci.techniqueemployeeid
WHERE cci.togetherflag = '{0}' {1}

UNION ALL

SELECT subc.containerid,subc.containername,subc.teamname,subc.qty,subc.teamname,subc.workflowid,subc.techniqueemployeeid,ee.fullname containertechemp,
       CASE WHEN cq.techconfirmemployee IS NOT NULL AND cq.checkconfirmemployee IS NOT NULL THEN '已确认' ELSE '未确认' END status,
       e.fullname techemp,cq.techconfirmdate,cq.techconfirmnote,e2.fullname checkemp,cq.checkconfirmdate,cq.checkconfirmnote,cq.spindlenode
FROM containercurrentinfo cci
LEFT JOIN containersubcontainer csc ON csc.containerid = cci.containerid
LEFT JOIN containercurrentinfo subc ON subc.containerid = csc.subcontainerid 
LEFT JOIN containerqualityensure cq ON cq.containerid = subc.containerid
LEFT JOIN employee e ON e.employeeid = cq.techconfirmemployee
LEFT JOIN employee e2 ON e2.employeeid = cq.checkconfirmemployee
LEFT JOIN employee ee ON ee.employeeid = subc.techniqueemployeeid
WHERE cci.togetherflag = '{0}' AND subc.containerstatus = 1 {2}
";
        string zdggFilter = string.Empty;
        if (!string.IsNullOrWhiteSpace(context.Request.Form["printType"].ToString()) && context.Request.Form["printType"].ToString().Equals("1"))
        {
            zdggFilter = @" and exists (
            select 1 from workflowstep ws 
            left join stepcheckpoint sc on sc.workflowstepid =ws.workflowstepid 
            where ws.workflowid={0} and sc.checktype ='5'
            )";
        }
        strSql = string.Format(strSql, context.Request.Form["togetherflag"].ToString(),
            string.Format(zdggFilter, "decode(cci.containerstatus,1,cci.workflowid,cci.bsworkflowid)"), string.Format(zdggFilter, "decode(subc.containerstatus,1,subc.workflowid,subc.bsworkflowid)"));
        DataTable result = DatabaseHelper.Query_ReturnDatTable(strSql);
        foreach (DataColumn col in result.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    string GetEmployeeResourcesSql(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        DataTable dtEmployee = dtPostData.DefaultView.ToTable(true, "employeeid");
        string strQueryList = "(";
        foreach (DataRow dr in dtEmployee.Rows)
        {
            strQueryList += string.Format("'{0}',", dr["employeeid"].ToString());
        }
        if (strQueryList != "(")
        {
            strQueryList = strQueryList.Substring(0, strQueryList.Length - 1) + ")";
        }
        else
        {
            strQueryList = "('')";
        }
        string sql = @"SELECT e.employeeid,e.fullname,e.employeename,rd.resourceid,rd.resourcename,rd.description,rd.notes,rf.resourcefamilyid,rf.resourcefamilyname
                    FROM employeeresourcelist erl 
                    LEFT JOIN Resourcedef rd ON rd.resourceid = erl.resourcelistid 
                    LEFT JOIN employee e ON e.employeeid = erl.employeeid
                    LEFT JOIN Resourcefamily rf ON rf.resourcefamilyid = rd.resourcefamilyid
                    WHERE erl.employeeid IN {0}";
        sql = string.Format(sql, strQueryList);
        return sql;
    }

    //保存技术员确认信息
    void saveTeachConfirmData(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string techconfirmemployee = context.Request.Form["techconfirmemployee"].ToString();//技术员
            string techconfirmdate = context.Request.Form["techconfirmdate"].ToString().Trim();//技术确认日期
            string techconfirmnote = context.Request.Form["techconfirmnote"].ToString().Trim();//技术确认备注
            foreach (DataRow dr in dtPostData.Rows)
            {
                string containerid = dr["containerid"].ToString();
                string sql = string.Format("SELECT t.* FROM containerqualityensure t WHERE t.containerid = '{0}'", containerid);
                DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
                if (dt.Rows.Count == 0)
                {
                    sql = @"
INSERT INTO containerqualityensure(id,containerid,techconfirmemployee,techconfirmdate,techconfirmnote)
VALUES('{0}','{1}','{2}',to_date('{3}','yyyy/mm/dd'),'{4}')";
                    sql = string.Format(sql,
                        Guid.NewGuid().ToString(),//唯一id
                        containerid,
                        techconfirmemployee,
                        techconfirmdate,
                        techconfirmnote
                        );
                    DatabaseHelper.ExecuteSql(sql);
                }
                else
                {
                    sql = @"
UPDATE containerqualityensure t 
SET t.techconfirmemployee = '{1}',t.techconfirmdate = to_date('{2}','yyyy/mm/dd'),t.techconfirmnote = '{3}'
WHERE t.containerid = '{0}'";
                    sql = string.Format(sql, containerid, techconfirmemployee, techconfirmdate, techconfirmnote);
                    DatabaseHelper.ExecuteSql(sql);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //保存检验员确认信息
    void saveCheckConfirmData(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            string checkconfirmemployee = context.Request.Form["checkconfirmemployee"].ToString();//检验员
            string checkconfirmdate = context.Request.Form["checkconfirmdate"].ToString().Trim();//检验确认日期
            string checkconfirmnote = context.Request.Form["checkconfirmnote"].ToString().Trim();//检验确认备注
            string spindlenode = context.Request.Form["spindlenode"].ToString().Trim();//锭节点
            string groupname = context.Request.Form["groupname"].ToString().Trim();//组别

            foreach (DataRow dr in dtPostData.Rows)
            {
                string containerid = dr["containerid"].ToString();
                string sql = string.Format("SELECT t.* FROM containerqualityensure t WHERE t.containerid = '{0}'", containerid);
                DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
                if (dt.Rows.Count == 0)
                {
                    sql = @"
INSERT INTO containerqualityensure(id,containerid,checkconfirmemployee,checkconfirmdate,checkconfirmnote,spindlenode,groupname)
VALUES('{0}','{1}','{2}',to_date('{3}','yyyy/mm/dd'),'{4}','{5}','{6}')";
                    sql = string.Format(sql,
                        Guid.NewGuid().ToString(),//唯一id
                        containerid,
                        checkconfirmemployee,
                        checkconfirmdate,
                        checkconfirmnote,
                        spindlenode,
                        groupname
                        );
                    DatabaseHelper.ExecuteSql(sql);
                }
                else
                {
                    sql = @"
UPDATE containerqualityensure t 
SET t.checkconfirmemployee = '{1}',t.checkconfirmdate = to_date('{2}','yyyy/mm/dd'),t.checkconfirmnote = '{3}',t.spindlenode = '{4}',t.groupname = '{5}'
WHERE t.containerid = '{0}'";
                    sql = string.Format(sql, containerid, checkconfirmemployee, checkconfirmdate, checkconfirmnote, spindlenode, groupname);
                    DatabaseHelper.ExecuteSql(sql);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //移除技术确认
    void removeTeachConfirmData(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            uMESProcessResult result = new uMESProcessResult() { Result = true };
            ArrayList sqlList = new ArrayList();
            foreach (DataRow dr in dtPostData.Rows)
            {
                string containerid = dr["containerid"].ToString();
                if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM containerqualityensure cq WHERE cq.techconfirmemployee = '{0}' AND cq.containerid = '{1}'", m_UserInfo.EmployeeID, containerid)) == null)
                {
                    result.Result = false; result.Message = "选择的批次存在技术员不是当前登录人，无法移除。";
                    break;
                }
                string sql = @"
                        UPDATE containerqualityensure t 
                        SET t.techconfirmemployee = NULL,t.techconfirmdate = NULL,t.techconfirmnote = NULL
                        WHERE t.containerid = '{0}'";
                sql = string.Format(sql, containerid);
                sqlList.Add(sql);
                //DatabaseHelper.ExecuteSql(sql);
            }
            if (result.Result)
            {
                DatabaseHelper.ExecuteSqlTran(sqlList);
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    //移除技术确认
    void removeCheckConfirmData(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            uMESProcessResult result = new uMESProcessResult() { Result = true };
            ArrayList sqlList = new ArrayList();
            foreach (DataRow dr in dtPostData.Rows)
            {
                string containerid = dr["containerid"].ToString();
                if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM containerqualityensure cq WHERE cq.checkconfirmemployee = '{0}' AND cq.containerid = '{1}'", m_UserInfo.EmployeeID, containerid)) == null)
                {
                    result.Result = false; result.Message = "选择的批次存在检验员不是当前登录人，无法移除。";
                    break;
                }
                string sql = @"
                        UPDATE containerqualityensure t 
                        SET t.checkconfirmemployee = NULL,t.checkconfirmdate = NULL,t.checkconfirmnote = NULL,t.spindlenode = NULL,t.groupname = NULL
                        WHERE t.containerid = '{0}'";
                sql = string.Format(sql, containerid);
                sqlList.Add(sql);
                //DatabaseHelper.ExecuteSql(sql);
            }
            if (result.Result)
            {
                DatabaseHelper.ExecuteSqlTran(sqlList);
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    void getTeachOrCheckConfirmData(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            foreach (DataRow dr in dtPostData.Rows)
            {
                string containerid = dr["containerid"].ToString();
                string sql = @"SELECT t.* FROM containerqualityensure t WHERE t.containerid = '{0}'";
                sql = string.Format(sql, containerid);
                DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
                foreach (DataColumn col in dt.Columns)
                {
                    col.ColumnName = col.ColumnName.ToLower();
                }
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = dt }));
                break;
            }

        }
    }

    void savePrintSession(HttpContext context)
    {
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectedData"].ToString());
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            foreach (DataRow dr in dtPostData.Rows)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("containerID", dr["containerid"].ToString());
                para.Add("workflowID", dr["workflowid"].ToString());
                list.Add(para);
            }
            context.Session["ContainerWarrantyPrint"] = list;
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }
}